/**
 * Copyright (c) 2010 BullionXpress.com,
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */
package com.bullionxpress.server.feed;

import com.bullionxpress.shared.application.Messages;
import java.io.*;
import java.net.URL;
import com.bullionxpress.shared.model.Instrument;
import com.bullionxpress.shared.util.Log;
import java.text.DecimalFormat;
import java.util.StringTokenizer;

public class Feed {
    
    final static String btcFeedURL = "http://bcchanger.com/bitcoin_price_feed.php?feed_type=xml&currency=CAD";

    final static String feedURL = Messages.getProperty("feed.pm");
    final static String cadURL = Messages.getProperty("feed.cad");;

    private static double getCADPrice() {
        // TODO code application logic here
        try {
            URL url = new URL(cadURL);
            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                StringTokenizer tokenizer = new StringTokenizer(line, ",");
                tokenizer.nextToken();
                tokenizer.nextToken();
                double price = Double.parseDouble(tokenizer.nextToken());
                price = Math.abs(price);
                return price;
            }
        } catch (Exception ex) {
        }
        return -1;
    }
    
    public static double getBTCPrice(double units) {

        BufferedReader reader = null;
        try {
            URL url = new URL(btcFeedURL);
            reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String buf = "";
            String S = "";
            while ((buf = reader.readLine()) != null) {
                S += buf;
            }
            String tok = "<value>";
            int ptr = S.indexOf(tok);
            String str = S.substring(ptr+tok.length(), S.length());
            //System.out.println(str);
            int eptr = str.indexOf("<");
            String data = str.substring(0,eptr);
            //System.out.println(data);
            double price = Double.parseDouble(data);
            //System.out.println(price);
            return price*units;
        } catch (IOException ex) {
            Log.info(ex);
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                Log.info(ex);
            }
        }
        return -1;

    }

    private static double getSilverPrice(double grams) {

        BufferedReader reader = null;
        try {
            URL url = new URL(feedURL);
            reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String buf = "";
            while ((buf = reader.readLine()) != null) {
                if (buf.indexOf("<td>Silver</td>") != -1) {
                    buf = reader.readLine();
                    int p = buf.indexOf("td>");
                    int e = buf.indexOf("</");
                    String tok = buf.substring(p + 3, e);
                    tok = tok.trim();
                    double CAD = getCADPrice();
                    double silverPrice = Double.parseDouble(tok);
                    
                    silverPrice *= CAD;
                    return (silverPrice / 31.1) * grams;
                }
            }
        } catch (IOException ex) {
            Log.info(ex);
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                Log.info(ex);
            }
        }
        return -1;

    }

    private static double getGoldPrice(double grams) {

        BufferedReader reader = null;
        try {
            URL url = new URL(feedURL);
            reader = new BufferedReader(new InputStreamReader(url.openStream()));
            String buf = "";
            while ((buf = reader.readLine()) != null) {
                if (buf.indexOf("<td>Gold</td>") != -1) {
                    buf = reader.readLine();
                    int p = buf.indexOf("td>");
                    int e = buf.indexOf("</");
                    String tok = buf.substring(p + 3, e);
                    tok = tok.trim();
                    double CAD = getCADPrice();
                    double goldPrice = Double.parseDouble(tok);
                    
                    goldPrice *= CAD;
                    return (goldPrice / 31.1) * grams;
                    
                }
            }
        } catch (IOException ex) {
            Log.info(ex);
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                Log.info(ex);
            }
        }
        return -1;

    }

    public static double getPriceByInstrument(Instrument instrument, boolean raw) {
        // TODO code application logic here
        try {
            if( instrument == null ){
                throw new IllegalArgumentException("Instrument is null");
            }
            if (raw == true) {
                if (instrument.getSymbol().equals("GOLD")) {
                    double gp = -1;
                    gp = getGoldPrice(1);
                    if( gp != -1 ){
                        return gp;
                    }
                }
                if (instrument.getSymbol().equals("SILVER")) {
                    double sp = -1;
                    sp = getSilverPrice(1);
                    if( sp != -1 ){
                        return sp;
                    }
                }
                if (instrument.getSymbol().equals("BTC")) {
                    double sp = -1;
                    sp = getBTCPrice(1);
                    if( sp != -1 ){
                        return sp;
                    }
                }
            } 
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return lastGoldPrice;
    }

    public static double getPriceByGramAndKarat(double price, double gram, double karat) {
        double pricePerGram = ((price) * gram) * (karat / 24);
        return pricePerGram;
    }
    static double lastGoldPrice = -1;
    static double lastSilverPrice = -1;
    static double lastCADPrice = -1;

    public static void main(String[] args) {
        System.out.println(getCADPrice());
        Instrument gold = new Instrument("GOLD");
        gold.setSymbol("GOLD");
        Instrument silver = new Instrument("SILVER");
        silver.setSymbol("SILVER");
        System.out.println(getPriceByInstrument(gold, true) * 31.1);
        System.out.println(getPriceByInstrument(silver, true));
    }
}
